import log4js from 'log4js';
import * as nodemailer from 'nodemailer';
import config from '../config';
import { db } from './nedb';
import { PostDTO } from '../index';

const errorLog = log4js.getLogger('error');
const logger = log4js.getLogger();
const type = [
  '办公室',
  '住宅-公寓',
  '住宅-别墅',
  '厂房',
  '汽车',
  '医疗机构',
  '学校',
  '商场',
  '酒店',
  '其他'
];

const template = (data: PostDTO): string => `
  姓名: ${data.name}
  邮箱: ${data.email}
  联系电话: ${data.telphone || ''}
  公司: ${data.company || ''}
  职位: ${data.job || ''}
  城市: ${data.city || ''}
  地址: ${data.address || ''}
  面积: ${data.area || ''}
  类型: ${type[data.type]}

  留言: ${data.message || ''}
`;

const client = nodemailer.createTransport(config.mail);

export const sendError = (error: string) => {
  const message = {
    from: `"异常报告"<${config.mail.auth.user}>`,
    to: 'mosaice@qq.com',
    subject: '来自官网留言',
    text: error
  };

  client.sendMail(message, (error, info) => {
    const now = new Date().toLocaleString();
    if (error) {
      errorLog.error(`[邮件发送失败] ${now}:${error.message}`);
    }
  });
};

export const sendMail = (data: PostDTO) => {
  const message = {
    from: `"官网邮件"<${config.mail.auth.user}>`,
    // to: 'mosaice@qq.com',
    to: 'solutions@purearea.com.cn',
    subject: '来自官网留言',
    text: template(data)
  };

  client.sendMail(message, (error, info) => {
    const now = new Date().toLocaleString();
    if (error) {
      errorLog.error(`[邮件发送失败] ${now}:${error.message}`);
    }

    logger.info(`[邮件发送成功]${now}：${info}`);
    db.insert({ ...data, time: now }, err => {
      if (err) {
        errorLog.error(`[存储信息失败] ${now}:${err.message}`);
      }
    });
  });
};
